package com.ruoyi.system.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.constant.IntergalType;
import com.ruoyi.common.core.constant.SigninConstants;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.IntegralVo;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 个人积分统计表增删改查Controller
 * 
 * @author hyb
 * @date 2023-02-18
 */
@RestController
@RequestMapping("/personIntergal")
public class PersonalIntegralController extends BaseController
{
    @Autowired
    private IPersonalIntegralService personalIntegralService;


    @Autowired
    private IActivityService activityService;

    @Autowired
    private ISigninService signinService;

    @Autowired
    private ISchoolRoleService schoolRoleService;

    @Autowired
    private IIntergalService iIntergalService;


    @Autowired
    private IIntergalRuleService iIntergalRuleService;

    @Autowired
    private IUserDetailService detailService;

    /*
    * 个人积分统计柱状图数据
    * */
    @Transactional(rollbackFor = Exception.class)
//    @RequiresPermissions("personIntergal:personIntergal:listMe")
    @GetMapping("/listMe")
    public AjaxResult listMe(){
        Long userId = SecurityUtils.getUserId();
        PersonalIntegral personalIntegral = new PersonalIntegral();
        personalIntegral.setUserId(userId);
        List<PersonalIntegral> personalIntegrals = personalIntegralService.selectPersonalIntegralList(personalIntegral);
        personalIntegral=personalIntegrals.size()==0?null:personalIntegrals.get(0);
        //自己部门下的积分统计规则
        SchoolRole schoolRole = new SchoolRole();
        schoolRole.setUserId(userId);
        List<SchoolRole> schoolRoles = schoolRoleService.selectSchoolRoleList(schoolRole);
        if (schoolRoles.size()==0){
            return AjaxResult.error("您未认证学校信息,无法统计");
        }
        schoolRole=schoolRoles.get(0);
        IntergalRule intergalRule = new IntergalRule();
        intergalRule.setDeptId(schoolRole.getDeptId());
        List<IntergalRule> intergalRules = iIntergalRuleService.selectIntergalRuleList(intergalRule);
        if (intergalRules.size()==0){
            return AjaxResult.error("不存在您的部门信息");
        }
        intergalRule=intergalRules.get(0);
        Map<String,Object> map=new HashMap<>();
        map.put("personalIntegral",personalIntegral);
        map.put("intergalRule",intergalRule);
        return AjaxResult.success().put("map",map);

    }

    /*
    * 给某个人发放积分
    * */
    @Transactional(rollbackFor = Exception.class)
    @RequiresPermissions("personIntergal:personIntergal:grant")
    @PostMapping("/grant")
    public AjaxResult grant(@RequestBody IntegralVo integral){
        //先查你是否是这个活动的负责人
        String activityId = integral.getActivityId();
        Activity activity = activityService.selectActivityById(Long.parseLong(activityId));

        if (activity==null){
            return AjaxResult.error("活动不存在");
        }
        if (!activity.getUserId().equals(SecurityUtils.getUserId())){
            return AjaxResult.error("你不是该活动的负责人,无法发放积分");
        }
        BigDecimal preIntegral = activity.getPreIntegral();
        if (preIntegral.equals(new BigDecimal("0"))){
            return AjaxResult.error("该活动积分已为0");
        }

        //再查这个用户是否签到成功
        String userId = integral.getUserId();
        Signin signin = new Signin();
        signin.setUserId(Long.parseLong(userId));
        signin.setActivityId(Long.parseLong(activityId));
        signin=signinService.selectSigninByUserIdAndActivityId(signin);
        if (signin==null){
            return AjaxResult.error("该用户未签到");
        }
        if (!signin.getStatus().equals(SigninConstants.SUCCESS)){
            return AjaxResult.error("该用户未签到成功,无法发放积分,您可以对其补签");
        }
        //先插入分发记录
        //先查认证信息,再查签到信息
        SchoolRole schoolRole = new SchoolRole();
        schoolRole.setUserId(Long.parseLong(userId));
        List<SchoolRole> schoolRoles = schoolRoleService.selectSchoolRoleList(schoolRole);
        if (schoolRoles.size()==0){
            return AjaxResult.error("用户未认证学校信息");
        }
        schoolRole=schoolRoles.get(0);
        Intergal gal = new Intergal();
        gal.setUserId(schoolRole.getUserId());
        gal.setActivityId(activity.getId());

        //是否已颁发
        List<Intergal> intergals = iIntergalService.selectIntergalList(gal);
        if (intergals.size()!=0){
            return AjaxResult.error("该用户已颁发积分");
        }
        gal.setUserName(SecurityUtils.getUsername());
        gal.setRealName(schoolRole.getName());
        gal.setUserNumber(schoolRole.getNumber());
        gal.setActivityName(activity.getName());
        gal.setScore(new BigDecimal(integral.getScore()));
        gal.setSigninType(Long.parseLong(signin.getPf1()));
        gal.setGrantTime(DateUtils.getNowDate());
        gal.setType(activity.getClassification());
        //插入
        iIntergalService.insertIntergal(gal);

        //更新用户detail表的积分总数
        UserDetail userDetail = new UserDetail();
        userDetail.setUserId(Long.parseLong(userId));
        userDetail.setPf1(new BigDecimal(integral.getScore())+"");
        detailService.updateUserDetailAddCount(userDetail);

        //更新用户的个人积分的记录表
        //先查有没有,没有就插入,有就更新
        PersonalIntegral personalIntegral = new PersonalIntegral();
        personalIntegral.setUserId(Long.parseLong(userId));
        List<PersonalIntegral> personalIntegrals = personalIntegralService.selectPersonalIntegralList(personalIntegral);
        personalIntegral.setRealName(schoolRole.getName());
        personalIntegral.setUserNumber(schoolRole.getNumber());
        personalIntegral.setUserName(SecurityUtils.getUsername());
        personalIntegral.setSex(Long.parseLong(schoolRole.getSex()));
        String classification = activity.getClassification();
        BigDecimal bigDecimal = new BigDecimal(integral.getScore());
        if (classification.equals(IntergalType.TYPE0.getType())){
            personalIntegral.setMoralityYes(bigDecimal);
        }else if (classification.equals(IntergalType.TYPE1.getType())){
            personalIntegral.setMoralityNo(bigDecimal);
        }else if (classification.equals(IntergalType.TYPE2.getType())){
            personalIntegral.setIntelligenceYes(bigDecimal);
        }else if (classification.equals(IntergalType.TYPE3.getType())){
            personalIntegral.setIntelligenceNo(bigDecimal);
        }else if (classification.equals(IntergalType.TYPE4.getType())){
            personalIntegral.setSportYes(bigDecimal);
        }else if (classification.equals(IntergalType.TYPE5.getType())){
            personalIntegral.setSportNo(bigDecimal);
        }else if (classification.equals(IntergalType.TYPE6.getType())){
            personalIntegral.setArtYes(bigDecimal);
        }else if (classification.equals(IntergalType.TYPE7.getType())){
            personalIntegral.setArtNo(bigDecimal);
        }else if (classification.equals(IntergalType.TYPE8.getType())){
            personalIntegral.setWorkYes(bigDecimal);
        }else {
            personalIntegral.setWorkNo(bigDecimal);
        }
        if (personalIntegrals.size()==0){
            personalIntegralService.insertPersonalIntegral(personalIntegral);
        }else{
            personalIntegral.setId(personalIntegrals.get(0).getId());
            personalIntegralService.updatePersonalIntegral(personalIntegral);
        }
        //修改活动的积分数量
        activity.setPreIntegral(activity.getPreIntegral().subtract(bigDecimal));
        activity.setLastIntegral(activity.getLastIntegral().add(bigDecimal));
        activityService.updateActivity(activity);
        //更新签到表状态
        Signin sg = new Signin();
        sg.setId(signin.getId());
        sg.setStatus(SigninConstants.INTERGAL);
        signinService.updateSignin(sg);

        return AjaxResult.success();
    }

    /**
     * 查询个人积分统计表增删改查列表
     */
    @RequiresPermissions("personIntergal:personIntergal:list")
    @GetMapping("/list")
    public TableDataInfo list(PersonalIntegral personalIntegral)
    {
        startPage();
        List<PersonalIntegral> list = personalIntegralService.selectPersonalIntegralList(personalIntegral);
        return getDataTable(list);
    }

    /**
     * 导出个人积分统计表增删改查列表
     */
    @RequiresPermissions("personIntergal:personIntergal:export")
    @Log(title = "个人积分统计表增删改查", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PersonalIntegral personalIntegral)
    {
        List<PersonalIntegral> list = personalIntegralService.selectPersonalIntegralList(personalIntegral);
        ExcelUtil<PersonalIntegral> util = new ExcelUtil<PersonalIntegral>(PersonalIntegral.class);
        util.exportExcel(response, list, "个人积分统计表增删改查数据");
    }

    /**
     * 获取个人积分统计表增删改查详细信息
     */
    @RequiresPermissions("personIntergal:personIntergal:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(personalIntegralService.selectPersonalIntegralById(id));
    }

    /**
     * 新增个人积分统计表增删改查
     */
    @RequiresPermissions("personIntergal:personIntergal:add")
    @Log(title = "个人积分统计表增删改查", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PersonalIntegral personalIntegral)
    {
        return toAjax(personalIntegralService.insertPersonalIntegral(personalIntegral));
    }

    /**
     * 修改个人积分统计表增删改查
     */
    @RequiresPermissions("personIntergal:personIntergal:edit")
    @Log(title = "个人积分统计表增删改查", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PersonalIntegral personalIntegral)
    {
        return toAjax(personalIntegralService.updatePersonalIntegral(personalIntegral));
    }

    /**
     * 删除个人积分统计表增删改查
     */
    @RequiresPermissions("personIntergal:personIntergal:remove")
    @Log(title = "个人积分统计表增删改查", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(personalIntegralService.deletePersonalIntegralByIds(ids));
    }
}
